package system

import (
	"time"

	genSysCaptcha "admin_template/bff/admin/hertz_gen/system/sys_captcha"
	"admin_template/bff/admin/internal/service/system"
	"github.com/mojocn/base64Captcha"

	"admin_template/bff/admin/internal/base/data"
)

var globalCacheStore base64Captcha.Store

func NewCacheStore(length, cacheExpiresTime int) base64Captcha.Store {
	if globalCacheStore == nil {
		globalCacheStore = base64Captcha.NewMemoryStore(length, time.Duration(cacheExpiresTime)*time.Second)
	}
	return globalCacheStore
}

type captchaRepo struct {
	*data.Data
	captcha *base64Captcha.Captcha
}

func NewCaptchaRepo(data *data.Data) system.CaptchaRepo {
	driver := base64Captcha.NewDriverDigit(
		data.Config.SystemConfig.Captcha.ImgHeight,
		data.Config.SystemConfig.Captcha.ImgWidth,
		data.Config.SystemConfig.Captcha.KeyLong,
		0.7, 80,
	)
	return &captchaRepo{
		Data: data,
		captcha: base64Captcha.NewCaptcha(
			driver,
			NewCacheStore(
				data.Config.SystemConfig.Captcha.CacheLength,
				data.Config.SystemConfig.Captcha.CacheExpiresTime,
			),
		),
	}
}

func (repo *captchaRepo) Get() (*genSysCaptcha.Info, error) {
	id, b64s, _, err := repo.captcha.Generate()
	if err != nil {
		return nil, err
	}
	return &genSysCaptcha.Info{
		CaptchaId: id,
		ImgPath:   int32(repo.Config.SystemConfig.Captcha.KeyLong),
		ImgData:   b64s,
	}, nil
}

func (repo *captchaRepo) Verify(dataID string, captcha string) bool {
	return repo.captcha.Verify(dataID, captcha, true)
}
